#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：刘骏轩2025讯飞 
@File ：get_preval.py
@Author ：ljx
@Date ：2025/7/29 上午11:49 
"""

import cv2
import numpy as np
from LineFind import LineFinder


# 回调函数，x 表示滑块的位置
def nothing(x):
    pass


def create_Trackbar():
    cv2.namedWindow('Trackbar')

    # 创建 LAB 六个滑动条
    cv2.createTrackbar('L_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('L_MIN', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('A_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('A_MIN', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('B_MAX', 'Trackbar', 0, 255, nothing)
    cv2.createTrackbar('B_MIN', 'Trackbar', 0, 255, nothing)

    cv2.createTrackbar('thresh', 'Trackbar', 0, 255, nothing)

    # 设置初始值
    cv2.setTrackbarPos('L_MAX', 'Trackbar', 255)
    cv2.setTrackbarPos('L_MIN', 'Trackbar', 180)
    cv2.setTrackbarPos('A_MAX', 'Trackbar', 180)
    cv2.setTrackbarPos('A_MIN', 'Trackbar', 120)
    cv2.setTrackbarPos('B_MAX', 'Trackbar', 180)
    cv2.setTrackbarPos('B_MIN', 'Trackbar', 120)

    cv2.setTrackbarPos('thresh', 'Trackbar', 180)


if __name__ == '__main__':
    create_Trackbar()
    cap = cv2.VideoCapture(0)
    solver = LineFinder()

    while 1:
        ret, frame = cap.read()
        frame = cv2.flip(frame, 1)

        if not ret:
            continue

        # frame = cv2.imread('pic/test_0.jpg')

        # 获取滑块的值
        l_max = cv2.getTrackbarPos('L_MAX', 'Trackbar')
        l_min = cv2.getTrackbarPos('L_MIN', 'Trackbar')
        a_max = cv2.getTrackbarPos('A_MAX', 'Trackbar')
        a_min = cv2.getTrackbarPos('A_MIN', 'Trackbar')
        b_max = cv2.getTrackbarPos('B_MAX', 'Trackbar')
        b_min = cv2.getTrackbarPos('B_MIN', 'Trackbar')

        thresh = cv2.getTrackbarPos('thresh', 'Trackbar')

        lower = np.array([l_min, a_min, b_min])
        upper = np.array([l_max, a_max, b_max])

        solver.lab_upper = upper
        solver.lab_lower = lower
        solver.thresh = thresh

        calibration = solver.calibration(frame)
        cut_img = calibration[solver.height - solver.cut_height:solver.height, 0:solver.width]
        # orign_lab = solver.do_preimg(frame, way=2)
        # orign_gray = solver.do_preimg(frame, way=1)

        cal_lab = solver.do_pre(cut_img, way=2)
        cal_gray = solver.do_pre(cut_img, way=1)

        # cv2.imshow('orign', calibration)
        # cv2.imshow('orign',frame)
        # cv2.imshow('orign_lab', orign_lab)
        # cv2.imshow('orign_gray', orign_gray)
        cv2.imshow('cal',calibration)
        cv2.imshow('cal_lab', cal_lab)
        cv2.imshow('cal_gray', cal_gray)

        # print(solver.lab_upper)
        # print(solver.lab_lower)
        # print(solver.thresh)
        cv2.waitKey(1)
